package cn.codergege.packagename.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.codergege.packagename.model.Department;
import cn.codergege.packagename.model.Employee;
import cn.codergege.packagename.service.DepartmentService;
import cn.codergege.packagename.service.EmployeeService;

@Controller
@RequestMapping("/employee")
public class EmployeeHandler {
	final Logger log = LoggerFactory.getLogger(EmployeeHandler.class);

	@Resource
	private EmployeeService employeeService;
	@Resource
	private DepartmentService departmentService;

	@ModelAttribute
	public void queryEmployee(@RequestParam(value = "id", required = false) Integer id, Map<String, Object> map) {
		// id 不为空, 说明是 PUT 请求, 那就从数据库中获取 employee 放入 map.
		if (id != null) {
			Employee employee = employeeService.selectByPrimaryKey(id);
			map.put("employee", employee);
		}
	}

	@RequestMapping("/emps")
	public String list(Map<String, Object> map) {

		List<Employee> employees = employeeService.getAll();
		map.put("employees", employees);

		return "forward:/WEB-INF/employee/list.jsp";
	}

	@RequestMapping(value = "/emp", method = RequestMethod.GET)
	public String add(Map<String, Object> map) {

		fillMap(map);

		// springmvc form 表单 modelAttribute="employee"
		// 所以需要一个 employee 对象
		map.put("employee", new Employee());

		return "forward:/WEB-INF/employee/add.jsp";
	}

	@RequestMapping(value = "/emp", method = RequestMethod.POST)
	public String add(@Valid Employee employee, BindingResult result, Map<String, Object> map) {

		// 验证有错误
		// if(result.getErrorCount() > 0) {
		if (result.hasErrors()) {
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError error : fieldErrors) {
				log.info("----> " + error.getField() + ": " + error.getDefaultMessage());
			}
			fillMap(map);
			return "forward:/WEB-INF/employee/add.jsp";
		}

		// 插入数据库失败
		try {
			employeeService.insertSelective(employee);
		} catch (Exception e) {
			e.printStackTrace();
			//todo  转入异常页面
		}

		return "redirect:/employee/emps";
	}

	// delete
	@RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Integer id) {
		try {
			employeeService.deleteByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/employee/emps";
	}

	// update
	@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") Integer id, Map<String, Object> map) {
		fillMap(map);
		Employee employee = employeeService.selectByPrimaryKey(id);
		map.put("employee", employee);
		return "forward:/WEB-INF/employee/update.jsp";
	}

	@RequestMapping(value = "/emp", method = RequestMethod.PUT)
	public String update(@Valid Employee employee, BindingResult result, Map<String, Object> map) {
		if (result.hasErrors()) {
			for (FieldError error : result.getFieldErrors()) {
				log.info("----> " + error.getField() + ": " + error.getDefaultMessage());
			}
			fillMap(map);
			return "forward:/WEB-INF/employee/update.jsp";
		}
		
		try {
			employeeService.updateByPrimaryKeySelective(employee);
		} catch (Exception e) {
			e.printStackTrace();
			//todo  转入异常页面
		}

		return "redirect:/employee/emps";
	}

	private void fillMap(Map<String, Object> map) {

		Map<String, String> genders = new HashMap<String, String>();
		genders.put("1", "男");
		genders.put("0", "女");
		map.put("genders", genders);

		List<Department> departments = departmentService.getAll();
		map.put("departments", departments);

	}
}
